/**
 * 描述: 业务逻辑处理 - 单词接口
 * 作者: wz
 * 日期: 2023-12-25
*/


const { querySql, formatTime, innerUploadFile } = require('../utils/index');
const boom = require('boom');
const { body, validationResult } = require('express-validator');
const { 
  CODE_ERROR,
  CODE_SUCCESS, 
} = require('../utils/constant');

// 查询所有视频列表
async function getVideoList(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
    next(boom.badRequest(msg));
  } else {

    let { pageSize, pageNo, params } = req.body;
    
    // 默认值
    pageSize = pageSize ? pageSize : 1;
    pageNo = pageNo ? pageNo : 1;

    let query = `select id from sys_video d`;
    let paramsStr = ' where delete_flag=0';
    if( params){
      if( params.gmt_create){
        if( params.gmt_create.length > 0 && params.gmt_create[0]){
          paramsStr += ' and d.gmt_create >=\'' + params.gmt_create[0] + '\'';
          if( params.gmt_create.length > 1&& params.gmt_create[1]){
            paramsStr += ' and d.gmt_create <=\'' + params.gmt_create[1] + '\'';
          }
        }
      }
      if( params.name){
        paramsStr += ' and name like \'%' + params.name + '%\'';
      }
    }

    try{
      let data = await querySql(query + paramsStr)
    	// console.log('任务列表查询===', data);
      if (!data || data.length === 0) {
        res.json({ 
        	code: CODE_SUCCESS, 
        	msg: '暂无数据', 
        	data: null 
        })
      } else {
        // 计算数据总条数
        let total = data.length; 
        // 分页条件 (跳过多少条)
        let n = (pageNo - 1) * pageSize;
        // 拼接分页的sql语句命令
        let query_3 = `select d.id,name,video_file,image,d.gmt_create from sys_video d`;
        query_3 += paramsStr;
        query_3 += ` order by d.gmt_create desc limit ${n} , ${pageSize}`;
        let result_3 = await querySql(query_3);
        if (!result_3 || result_3.length === 0) {
          res.json({ 
            code: CODE_SUCCESS, 
            msg: '暂无数据', 
            data: null 
          })
        } else {
          res.json({ 
            code: CODE_SUCCESS, 
            msg: '查询数据成功', 
            data: {
              rows: result_3,
              total: total,
              pageNo: parseInt(pageNo),
              pageSize: parseInt(pageSize),
            } 
          })
        }
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '暂无数据', 
        data: err 
      })
    }
  }
}

// 添加视频
async function addVideo(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { name, image, gmt_create, video_file} = req.body;
    if( !gmt_create || gmt_create.length === 0){
      gmt_create = formatTime(new Date());
    }
    if( !image){
      image = '';
    }
    if( !video_file){
      video_file = '';
    }

    const query = `insert into sys_video(name, image, gmt_create, video_file) values('${name}', '${image}', '${gmt_create}', '${video_file}')`;
    console.log(query)
    try{  
      let data = await querySql(query);
      // console.log('添加任务===', data);
      if (!data || data.affectedRows === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '添加数据失败', 
          data: null 
        })
      } else {
        // console.log('更新用户余额===', data1);
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '添加数据成功', 
          data: null 
        })
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '添加数据失败', 
        data: err 
      })
    }
  }
}

// 编辑词汇包
async function editVideo(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { id, name, image, gmt_create, video_file} = req.body;
    let query = `update sys_video set name='${name}'`;
    if( image){
      query += `, image='${image}'`
    }
    if( video_file){
      query += `, video_file='${video_file}'`
    }
    if( gmt_create){
      query += `, gmt_create='${gmt_create}'`
    }
    query += ` where id='${id}'`;
    
    try{
      let data = await querySql(query);
      // console.log('编辑设备===', data);
      if (!data || data.affectedRows === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '更新数据失败', 
          data: null 
        })
      } else {
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '更新数据成功', 
          data: null 
        })
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '更新数据失败', 
        data: err 
      })
    }
  }
}

// 删除视频
async function deleteVideo(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { id } = req.body;

    const query = `update sys_video set delete_flag=1 where id='${id}'`;
    try{
      let data = await querySql(query)
      // console.log('删除设备===', data);
      if (!data || data.affectedRows === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '删除数据失败', 
          data: null 
        })
      } else {
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '删除数据成功', 
          data: null 
        })
      }
    } catch( err) {
      res.json({ 
        code: CODE_ERROR, 
        msg: '删除数据失败', 
        data: err 
      })
    }
  }
}

module.exports = {
  getVideoList,
  addVideo,
  editVideo,
  deleteVideo,
}
